<template>
	<view class="">

		<view class="login" @click="islogin" :style="{'display':mask?'block':'none'}"></view>
		<!-- 导航条 -->
		<view class="cu-custom" :style="{height: $wanlshop.wanlsys().height + 'px' }">
			<view class="cu-bar bg-bgcolor fixed"
				:style="{ height: $wanlshop.wanlsys().height + 'px', paddingTop: $wanlshop.wanlsys().top + 'px'}">
				<view class="action" @click="showCityPicker">
					<text class="wlIcon-weizhi text-bold"></text>
					<text class="margin-left-xs">{{sameCity.name}}</text>
				</view>
				<view class="search-form round">
					<text class="wlIcon-sousuo1 text-bold" @click="handleSearch"></text>
					<input @confirm="confirm" :adjust-position="false" type="text" v-model="params.search"
						placeholder="搜索话题" confirm-type="search"></input>
				</view>

			</view>
		</view>

		<!--轮播图-->
		<view class="swiper-box" v-if="bannersList.length > 0">
			<swiper class="swiper" circular :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval"
				:duration="duration">
				<swiper-item v-for="(item, index) in bannersList" :key="index">
					<image :src="'https://adminshop.12sxb.cn'+item.url" mode="scaleToFill" style="width: 100%;"></image>
				</swiper-item>
			</swiper>
		</view>

		<!--公告-->
		<view class="notice-wrapper margin-tb-sm">
			<swiper class="notice-swiper" circular="true" vertical="true" autoplay="true" interval="3000">
				<swiper-item v-for="(item, index) in noticeList" :key="index">
					<!-- <uni-notice-bar show-icon :text="item"/> -->
					<view class="wanlpage-notice"
						style="background-color: rgb(255, 251, 232);color: rgb(222, 143, 28);padding: 4rpx 25rpx;">
						<text class="wlIcon wlIcon-notice margin-right-xs"></text>
						<text>{{item}}</text>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<!--话题列表选项-->
		<view class="wanl-user-tool margin-lr-bj">
			<view class="list text-sm grid col-4 wanl-gray-dark">
				<view v-for="(item ,index) in list" v-if="params.area=='谷城县'" :index="index" :key="index" @click="change(index,item)">
					<image :src="cdnurl + item.img" style="width: 60rpx;height: 60rpx"></image>
					<view class="" :class="activeiIndex === index ? 'active' : ''">{{item.text}}</view>
				</view>
				
				<view v-for="(item ,index) in list" v-if="params.area!=='谷城县' && notgc.includes(item.text)" :index="index" :key="index" @click="change(index,item)">
					<image :src="cdnurl + item.img" style="width: 60rpx;height: 60rpx"></image>
					<view class="" :class="activeiIndex === index ? 'active' : ''">{{item.text}}</view>
				</view>
			</view>
		</view>

		<!-- 话题内容列表 -->
		<!-- 主体 -->
		<block v-if="localList.length > 0">
			<wanl-local-list ref="findListRef" :dataList="localList" :last_page="last_page" :current_page="params.page"
				:isComment="common.appConfig.comment_switch" currentItemId="find" :height="wanlsys.windowHeight"
				:width="wanlsys.windowWidth - 48"></wanl-local-list>
		</block>
		<block v-if="localList.length === 0 && status !== 'loading'">
			<wanl-empty :text="empty" />
		</block>
		<uni-load-more v-if="localList.length > 0" :status="status" :content-text="contentText" />

		<!--底部悬浮按钮-->
		<view class="margin-bottom-lg" style="position: fixed;">
			<uni-fab ref="fab" :pattern="pattern" :content="content" horizontal="right" vertical="bottom"
				:direction="direction" @trigger="trigger" />
		</view>

		<!--定位选择城市-->
		<mpvue-city-picker :themeColor="themeColor" ref="mpvueCityPicker" :pickerValueDefault="cityPickerValueDefault"
			@onConfirm="onConfirm">
		</mpvue-city-picker>


		<uni-popup ref="redenvelopepopup">
			<view class="wrapper"
				style="background:#fff;background-image:url('https://adminshop.12sxb.cn/uploads/redbao.png');background-size: cover;width:600rpx;height:960rpx;border-radius:20rpx;">

				<image v-show="!getMoney" @click="getredenvelope"
					style="width:200rpx;height:200rpx;margin-left:200rpx;margin-top:680rpx;"
					src="https://adminshop.12sxb.cn/uploads/open.png"></image>


				<view v-if="getMoney" class="money"
					style="font-size:68rpx;font-weight: bold;color:gold;position:absolute;margin-top:780rpx;margin-left:200rpx;">
					{{getMoney}}元
				</view>
			</view>
		</uni-popup>

		<view class="edgeInsetBottom"></view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import config from "@/common/config/config.js";
	import WanlLocalList from '@/components/wanl-local/lists.vue'
	import WanlEmpty from '@/components/wanl-empty/wanl-empty.vue'
	import mpvueCityPicker from '@/components/mpvue-citypicker/mpvueCityPicker.vue'
	import qqmapwx from "@/static/js/qqmap-wx-jssdk.min.js"
	import Debounce from '@/utils/debounce.js'
	export default {
		computed: {
			...mapState(['common'])
		},
		components: {
			WanlEmpty,
			mpvueCityPicker,
			WanlLocalList
		},

		data() {
			return {
				getMoney: "",

				notgc:["热门事件","生活服务","闲置物品","招聘","促销信息"], //非谷城可见的菜单

				cdnurl: config.cdnurl,
				wanlsys: {},
				indicatorDots: true,
				autoplay: true,
				interval: 2000,
				duration: 500,
				bannersList: [],

				noticeList: [],

				list: [], //话题分类列表
				localList: [], //话题发布列表
				activeiIndex: 0,
				title: 'uni-fab',
				direction: 'horizontal',
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor: '#007AFF',
					iconColor: '#fff'
				},
				is_color_type: false,
				content: [{
						iconPath: '/static/images/tabbar/find.png',
						selectedIconPath: '/static/images/tabbar/findHL.png',
						path: `/pages/local/post`,
						text: '发布',
						active: false
					},
					{
						iconPath: '/static/images/tabbar/category.png',
						selectedIconPath: '/static/images/tabbar/categoryHL.png',
						path: `/pages/business`,
						text: '商城',
						active: false
					},
					{
						iconPath: '/static/images/tabbar/user.png',
						selectedIconPath: '/static/images/tabbar/userHL.png',
						path: '/pages/local/my',
						text: '我的',
						active: false
					}
				],
				sameCity: {
					name: ' 定位中..'
				},
				themeColor: '#007AFF',
				cityPickerValueDefault: [0, 0, 1],
				pickerText: '',
				params: {
					province: "",
					city: "",
					area: '',
					search: '',
					type_id: "",
					page: 1
				},
				reload: false, //判断是否上拉
				last_page: 0,
				status: 'loading',
				contentText: {
					contentdown: '',
					contentrefresh: '正在加载..',
					contentnomore: '没有更多数据了'
				},
				pagesNum: 0,
				empty: '暂未发布内容~',

				mask: false,
			
			}
		},
		mounted() {
			const sys = uni.getSystemInfoSync();
			this.wanlsys = {
				headTop: sys.statusBarHeight,
				windowWidth: sys.windowWidth,
				windowHeight: sys.windowHeight,
				windowBottom: 0
			};
			// #ifdef APP-NVUE
			this.wanlsys.windowBottom = sys.windowBottom;
			// #endif
		},




		async onShow() {

		},
		async onLoad() {
			let that = this;
			this.getAddress().then(res => {
				this.loadData();
			})
			this.reload = true;
			await this.getBanners();
			await this.getNotices()
			let userinfo = uni.getStorageSync("wanlshop:user");
			if (userinfo) {
				this.mask = false;
			} else {
				this.mask = true;
			}



		},

		// 监听上拉刷新
		onPullDownRefresh() {
			this.params.page = 1;
			this.reload = true;
			this.getAddress().then(res => {
				this.loadData();
			})
			// if (Object.keys(this.$store.state.common.addressData).length > 0) {
			// 	this.params.page = 1;
			// 	this.reload = true;
			// 	this.loadData();
			// } else {
			// 	uni.stopPullDownRefresh()
			// 	uni.showToast({
			// 		title: '位置获取失败',
			// 		icon: 'error'
			// 	})
			// 	this.status = 'noMore';
			// 	this.empty = '请重新获取定位~'
			// }
		},
		// 下拉加载
		onReachBottom() {
			if (this.params.page >= this.last_page) {
				this.status = 'noMore';
			} else {
				this.reload = false;
				this.contentText.contentdown = '上拉显示更多';
				this.params.page = this.params.page + 1; //页码+1
				this.status = 'loading';
				this.loadData();
			}
		},
		// 监听滚动
		onPageScroll(object) {
			if (object.scrollTop > this.WanlScroll) {
				this.scrollStype = false;
			} else {
				this.scrollStype = true;
			}
			if (object.scrollTop < 0) {
				this.scrollStype = false;
			}
			this.WanlScroll = object.scrollTop;
		},

		methods: {


			getredenvelope: Debounce(function() {
				let that = this;
				uni.request({
					url: "/wanlshop/local_life/getredenvelope",
					success: (res) => {
						console.log(res);
						if (res.data.tag == 1) {
							that.getMoney = res.data.money
							setTimeout(() => {
								that.$refs.redenvelopepopup.close();
							}, 3000)
						} else {
							uni.showToast({
								title: '网络错误,请重试',
								icon: 'none'
							});
						}

					}
				})

			}, 5000),



			islogin() {
				this.$wanlshop.auth('/pages/local');
			},


			//获取轮播图
			getBanners() {
				uni.request({
					url: '/common/banners?type=1',
					success: res => {
						this.bannersList = res.data
					}
				});
			},
			//获取公告
			getNotices() {
				uni.request({
					url: '/wanlshop/local_life/notices',
					success: res => {
						this.noticeList = res.data
					}
				});
			},
			//获取话题类型列表
			async loadData() {
				await uni.request({
					url: '/wanlshop/local_life/getTypes',
					type: 'get',
					success: res => {
						this.list = res.data
						this.params.type_id = this.params.type_id ? this.params.type_id : ""
						if (this.params.type_id == "") {
							this.activeiIndex = '';
						}
						this.getList();
					}
				});
			},

			// 获取大列表
			async getList() {
				console.log('获取大列表')

				let type_id = this.params.type_id
				let search = this.params.search
				let province = this.params.province
				let city = this.params.city
				let area = this.params.area


				if (!this.params.province) {
					let _addressData = uni.getStorageSync('addressData'); /*全局缓存相关的数据*/
					if (_addressData) {
						let addressData = JSON.parse(_addressData);
						if (addressData.province) {
							this.params.province = addressData.province;
							province = this.params.province;
						}
						if (addressData.city) {
							this.params.city = addressData.city;
							city = this.params.city;
						}
						if (addressData.district) {
							this.params.area = addressData.district;
							area = addressData.district;
						}
					}
				}




				if (province && city && area) {
					await uni.request({
						url: `/wanlshop/local_life/getList?type_id=${type_id}&province=${province}&city=${city}&area=${area}&search=${search}`,
						type: 'get',
						success: res => {
							uni.stopPullDownRefresh();
							this.status = res.data.total == 0 ? 'noMore' : 'more';
							this.localList = this.reload ? res.data.data : this.localList.concat(res.data
								.data); //数据 追加
							console.log('话题列表')
							this.params.page = res.data.current_page; //当前页码
							this.last_page = res.data.last_page; //总页码
						}
					});
				} else {
					this.status = 'noMore'
				}
			},

			//切换话题选项卡
			change(index, item) {
				//console.log(item)
				this.activeiIndex = index
				this.params.type_id = item.value
				this.getList()
			},

			//三个悬浮按钮点击
			trigger(e) {
				console.log(e.item);

				if (e.item.path == `/pages/business`) {
					uni.switchTab({
						url: e.item.path
					})
				} else if (e.item.path == `/pages/local/post`) {
					//先判断是否实名认证，否则先去实名认证
					//获取认证状态
					uni.request({
						url: '/wanlshop/passport/getPassportStatus',
						type: 'get',
						success: res => {
							if (res.data.status === 1) {
								uni.navigateTo({
									url: e.item.path
								})
							} else {
								uni.showModal({
									title: '提示',
									showCancel: false,
									content: '还未认证，请先完成个人认证或商家认证',
									success() {
										uni.navigateTo({
											url: '/pages/user/setting/personal'
										})
									}

								})
							}
						}
					});
				} else {
					uni.navigateTo({
						url: e.item.path
					})
				}
			},
			//显示地址三级联动
			showCityPicker() {
				this.$refs.mpvueCityPicker.show()
			},
			//三级联动
			onConfirm(e) {
				console.log(e);
				this.pickerText = JSON.stringify(e)
				let arr = e.label.split("-");
				this.sameCity.name = arr[arr.length - 1]

				console.log(arr);
				this.params.province = arr[0]
				this.params.city = arr[1]
				this.params.area = arr[2]
				console.log(this.params);
				this.$nextTick(() => {
					this.getList()
				})

				//console.log(this.params.area)
			},

			//搜索
			handleSearch() {
				//console.log(this.params.search)
				this.getList()
			},
			//监听搜索
			confirm(e) {
				this.params.search = e.detail.value
				this.getList()
			},

			// getAddress(){
			// 	if(!this.params.province && !this.params.city && !this.params.area){
			// 		let res = this.$store.state.common.addressData
			// 		if(Object.keys(res).length !== 0){					
			// 			this.params.province = res.address.province
			// 			this.params.city = res.address.city
			// 			this.params.area = res.address.district
			// 			this.sameCity.name = this.params.area
			// 		} 
			// 	}							
			// },



			getAddress() {
				let that = this;

				//测试段——————————————————————————————————————————————————
				if(config.test){
					return new Promise((resolve, reject) => {
					if (Object.keys(this.$store.state.common.addressData).length > 0) {
						resolve("ok");
					}
					let add = {
						latitude: 32.1524,
						longitude: 111.372,
						address: {
							city: "襄阳市",
							citycode: "0710",
							country: "中国",
							district: "谷城县",
							province: "湖北省",
							towncode: "420625500000",
							township: "薤山林场",
							latitude: 32.1524,
							street: "汉和路",
							longitude: 111.372,
							neighborhood: {
								name: "小吃街"
							}
						}
					};



					this.$store.commit('common/setAddress', add);

					let res2 = this.$store.state.common.addressData;
					if (Object.keys(res2).length !== 0) {
						that.params.province = res2.address.province
						that.params.city = res2.address.city
						that.params.area = res2.address.district
						that.sameCity.name = that.params.area

						if (res2.address.district == "谷城县") {
							if (uni.getStorageSync("wanlshop:user")) {

								//查询红包是否开启
								uni.request({
									url: "/wanlshop/local_life/redenvelopestatus",
									success(res) {
										if (res.data.canget == 1) {
											that.$refs.redenvelopepopup.open();
										}
									}
								})
							}

						}

					}


					resolve("ok")

				})
				}else{
					return new Promise((resolve,reject)=>{
						if(Object.keys(this.$store.state.common.addressData).length > 0){
							resolve("ok");
						}
						let qqmapsdk = new qqmapwx({
							key: '7LHBZ-JGG6W-72RR6-YDOJY-LNRCS-FVB55' //后端给的key
						});
					
					
						uni.getLocation({
							type: 'gcj02',
							geocode: true,
							isHighAccuracy: true,
							altitude: true,
							success: res => {
								const latitude = res.latitude;
								const longitude = res.longitude;
								// const latitude = 32.1637;
								// const longitude = 111.3922;
								qqmapsdk.reverseGeocoder({
									location: {
										latitude,
										longitude
									},
									success: function(res1) {
					
										let address = res1.result.address_component;
										address.township = res1.result.address_reference.town.title;
					
										try {
											address.neighborhoodname = res1.result.address_reference.street
												.title ? res1.result.address_reference.street.title : "";
											address.street = res1.result.address_reference.street.title ?
												res1.result.address_reference.street.title : "";
										} catch (err) {
											address.neighborhoodname = "";
											address.street = ""
										}
					
					
					
										address.neighborhood = {
											name: address.neighborhoodname
										};
										const addressData = {
											address: address,
											latitude: latitude,
											longitude: longitude,
											township: address.township,
											neighborhood: {
												name: address.neighborhoodname
											}
										}
										address.longitude = longitude;
										address.latitude = latitude;
					
										uni.setStorageSync('addressData', JSON.stringify(
											address)); /*全局缓存相关的数据*/
										that.$store.commit('common/setAddress', addressData);
					
										let res2 = that.$store.state.common.addressData
										if (Object.keys(res2).length !== 0) {
											that.params.province = res2.address.province
											that.params.city = res2.address.city
											that.params.area = res2.address.district
											that.sameCity.name = that.params.area
											if (res2.address.district == "谷城县") {
												if (uni.getStorageSync("wanlshop:user")) {
													//查询红包是否开启
													uni.request({
														url: "/wanlshop/local_life/redenvelopestatus",
														success(res) {
															if (res.data.canget == 1) {
																that.$refs.redenvelopepopup.open();
															}
														}
													})
												}
											}
					
										}
										resolve("ok")
					
									},
									fail: function(error) {
										reject(error)
									},
									complete: function(res) {
										resolve("ok")
									}
								})
					
							}
						});
					
					
					
					})
					
				}
				


				// 测试段——————————————————————————————————————————————————


				



			},




			oss(url, w = 120, h = 120, modenum = 2, type = '', format = 'jpg', resize = 'resize', multiple = 3) {
				let ossStc = this.$store.state.common.appUrl.oss;
				let image = '';
				let mode = ["m_lfit", "m_mfit", "m_fill", "m_fixed"];
				// 图像，自适应方向：1，渐进显示：1，转换格式：jpg，图片质量：q_90，图片锐化：50，浓缩图
				let rule = ["?x-oss-process=image", "auto-orient,1", "interlace,1", "format,jpg", "quality,q_90",
					"sharpen,50", "resize,m_fixed,w_120,h_120"
				];
				// 转换格式
				if (format == 'png') {
					rule[3] = ["format", "png"].join(",");
				}
				// 判断是否有高度
				if (w == 0) {
					rule[6] = [resize, mode[modenum], `h_${h * multiple}`].join(",");
				} else if (h == 0) {
					rule[6] = [resize, mode[modenum], `w_${w * multiple}`].join(",");
				} else {
					rule[6] = [resize, mode[modenum], `w_${w * multiple}`, `h_${h * multiple}`].join(",");
				}
				//当地址不存在
				if (url) {
					if ((/^data:image\//.test(url))) {
						image = url;
					} else if ((/^(http|https):\/\/.+/.test(url))) {
						rule.pop();
						image = url + rule.join("/");
					} else {
						image = ossStc + url + rule.join("/");
					}
				} else {
					if (type == 'transparent') {

					} else if (type == 'avatar') {
						image = ossStc + '/common/mine_def_touxiang_3x.png';
					} else {
						image = ossStc + '/common/img_default3x.png';
					}
				}
				return image;
			},

		}
	}
</script>
<style lang="scss" scoped>
	.login {
		top: 0;
		left: 0;
		position: fixed;
		background: transparent;
		min-height: 100vh;
		width: 100vw;
		z-index: 10000;
	}

	.notice-wrapper {
		height: 46rpx;
		/* 通告栏的高度 */
		overflow: hidden;
	}

	.notice-swiper {
		height: 100%;
		/* 设置swiper的高度为外层容器的高度 */
	}

	.swiper-box uni-image {
		width: 100%;
		height: 180px;
	}

	.swiper-box swiper {
		height: 180px;
	}

	.swiper-box swiper image {
		height: 180px;
	}

	/* 导航栏搜索框 */
	.cu-bar .search-form {
		background-color: #ebebeb;
	}

	::v-deep .empty-content {
		padding: 0;
	}

	::v-deep .uni-fab__circle--rightBottom {
		bottom: 160rpx;
	}

	::v-deep .uni-fab--rightBottom {
		bottom: 160rpx;
	}

	/* 工具箱 */
	/* 状态 */
	.wanl-user-tool .list {
		text-align: center;
	}

	.wanl-user-tool .list>view {
		margin-bottom: 28rpx;
		position: relative;
	}

	.wanl-user-tool .list>view .cu-tag {
		top: -8rpx;
		left: 80rpx;
		right: unset;
	}

	.wanl-user-tool .list text {
		display: block;
		font-size: 54rpx;
		margin-bottom: 8rpx;
	}


	.active {
		color: orange;
	}

	.grid-dynamic-box {
		margin-bottom: 15px;
	}


	.uni-app--showtabbar.uni-app--maxwidth>uni-page {
		padding-bottom: 50px;
		box-sizing: border-box;
	}


	.fade-enter-active,
	.fade-leave-active {
		transition: opacity 0.5s;
	}

	.fade-enter,
	.fade-leave-to

	/* .fade-leave-active for <2.1.8 */
		{
		opacity: 0;
	}
</style>